how to flatten a nested list in python

35

flat_list = [item for sublist in l for item in sublist]
flattened = [val for sublist in list_of_lists for val in sublist]
def flatten(t):
    return [item for sublist in t for item in sublist]
>>> from collections import Iterable
def flatten(lis):
     for item in lis:
         if isinstance(item, Iterable) and not isinstance(item, str):
             for x in flatten(item):
                 yield x
         else:        
             yield item

>>> lis = [1,[2,2,2],4]
>>> list(flatten(lis))
[1, 2, 2, 2, 4]
>>> list(flatten([[1, 2, 3], [4, 5, 6], [7, 8, 9]]))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Comments

Submit
0 Comments